package com.starsoft.quant.strategy;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.starsoft.quant.bean.QuantDetail;
import com.starsoft.quant.executor.StrategyReport;
import com.starsoft.smdc.bean.SmdcMarketDaily;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.trade.bean.TradeAcountStatus;
import com.starsoft.trade.order.Order;

public class SampleStragegy extends StrategyImpl {

	private static final Logger logger = LoggerFactory.getLogger(SampleStragegy.class);

	@Override
	public StrategyReport handle() {
		
		List<SmdcSecurity> securityList = context.getSecurityList();
		List<QuantDetail> details = new ArrayList<>();
		
		for (SmdcSecurity security : securityList) {
			try {
				QuantDetail report = analysis(security);
				details.add(report);
			} catch (Exception e) {
				logger.error(security.getSecId() + context.getCurrentDate() + e.getMessage());
			}
		}
		StrategyReport report = createReport(details);
		order(report);
		return report;
	}
	
	private QuantDetail analysis(SmdcSecurity security) {
		SmdcMarketDaily market = context.getMarket(security.getSecId());
		QuantDetail report = createDetail(security, 100.0);
		report.setCol1(market.getClosePrice() + "");
		return report;
	}
	
	private void order(StrategyReport report) {
		Integer acountId = context.getModelContext().getAcountId();
		TradeAcountStatus status = context.getAcountStatus();

		Double letfCash = status.getSummary().getCash();
		// buy
		if (letfCash > 100) {
			QuantDetail detail0 = report.getDetail(0);
			String secId = detail0.getId().getSecId();
			Double closePrice = context.getMarket(secId).getClosePrice();
			double num = (int) (letfCash / closePrice / 100)*100;
			Order order = new Order(secId, num, closePrice);
			letfCash += context.getOrderService().getOrderMoney(acountId, order);
			if (letfCash < 0) {
				num = num -100;
				order.setSecNum(num);
			}
			report.addOrder(order);
		}
	}
	
}
